import React, { Component } from 'react';
import { base, getMultiLang, createPage, cardCache, toast, promptBox, viewModel } from 'nc-lightapp-front';
import Inspection from 'epmp/exports/components/Inspection';
import config from './config';
import api from '../../common/api';
import _ from 'lodash-es'
import {
    onPageButtonClick,
    onSearchButtonClick,
    onBackButtonClick,
    onTableButtonClick,
    onTableAfterEvent,
    onTableBeforeEvent
} from './events';

const { setDefData, getDefData } = cardCache;
const { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
const { NCAffix, NCPopconfirm, NCFormControl, NCAnchor, NCScrollElement, NCScrollLink, NCDiv } = base;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.form(config.headcode);
        props.use.cardTable(config.bodycode);
        this.state = {
            multilang: {},
            isInspectionShowed: false,
            inspectionSourceData: {}
        };

        const searchParams = new URLSearchParams(window.location.hash.substring(window.location.hash.indexOf('?')));
        if (searchParams.get('bxdpk')) {
            props.setUrlParam({
                bxdpk: searchParams.get('bxdpk'),
                status: 'add'
            });
        } else if (searchParams.get('id')) {
            props.setUrlParam({
                id: searchParams.get('id')
            });
        } else {
            props.setUrlParam({
                status: 'browse'
            });
        }
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multilang,
            callback: json => {
                this.setState({ multilang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, data => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template);
                    });
                });
            }
        });
    }

    setMeta(meta) {
        const props = this.props;
        // const { setPageStatus } = this.props;
        meta[config.headcode].status = props.getUrlParam('status');

        meta[config.headcode].items.forEach(item => {
            if(item.attrcode === 'zy') {
                item.queryCondition = () => {

                    return {
                        crossrule_tradetype: props.form.getAllFormValue('head').rows[0].values['pk_tradetype'].value,
                        pk_org: props.form.getAllFormValue('head').rows[0].values['pk_org'].value,
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                }
            }
        })        

        meta[config.bodycode].items.forEach((item) => {
            if (!item.visible) return;
            if (item.itemtype === 'refer' && item.attrcode == 'assume_dept') {
                item.queryCondition = () => {
                    return {
                        pk_org: getDefData('pk_org', config.datasource),
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
        });

        meta[config.bodycode].items.push({
            label: this.state.multilang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '100px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                const status = props.getUrlParam('status');
                if (status === 'edit' || status === 'add') {
                    return props.button.createOprationButton(['table_delete'], {
                        area: config.innerButtonArea,
                        buttonLimit: 3,
                        onButtonClick: (props, key) => onTableButtonClick.call(this, props, key, text, record, index)
                    });
                }
                return null;
            }
        });

        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);
        // props.button.setPopContent(['delete', 'cancel'], '确认要执行该操作吗？');
    }

    initPage() {
        const props = this.props;
        // if (!getDefData('pk_org', config.datasourceCommon)) {
        //     api.getUserInfo().then((data) => {
        //         setDefData('pk_org', config.datasourceCommon, data.pk_org);
        //     });
        // }
        this.setPageStatus(props.getUrlParam('status'));
        this.loadData();
    }

    setPageStatus(status = 'browse') {
        const props = this.props;
        props.setUrlParam({ status });
        if (status === 'add') {
            props.form.setFormStatus(config.headcode, 'add');
            props.cardTable.setStatus(config.bodycode, 'add');
            props.button.setButtonDisabled(['edit', 'delete'], true);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel'], false);
        } else if (status === 'edit') {
            props.form.setFormStatus(config.headcode, 'edit');
            props.cardTable.setStatus(config.bodycode, 'edit');
            props.button.setButtonDisabled(['edit', 'delete'], true);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel'], false);
        } else {
            props.form.setFormStatus(config.headcode, 'browse');
            props.cardTable.setStatus(config.bodycode, 'browse');
            props.button.setButtonDisabled(['edit', 'delete'], false);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel'], true);
        }
    }

    loadData() {
        const props = this.props;
        const status = props.getUrlParam('status');
        let promise;
        if (status === 'add') {
            const bxdpk = props.getUrlParam('bxdpk');
            if (!bxdpk) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['bad_request']
                });
                return;
            }
            const params = {
                pkBx: bxdpk,
                appcode: config.appcode,
                pagecode: config.pagecode
            };
            promise = api.getDetailByReimbursement(params);
        } else {
            const id = props.getUrlParam('id');
            if (!id) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['bad_request']
                });
                return;
            }
            const params = {
                pks: id,
                appcode: config.appcode,
                pagecode: config.pagecode
            };
            promise = api.getDetailByPk(params);
        }

        promise.then(data => {
            // TODO 数据验证
            toast({
                color: 'success',
                content: this.state.multilang['query_success']
            });
            this.setData(data);
            // 报销单id
            // data.head[config.headcode].rows[0].values.src_id.value
        });
    }

    setData(data) {
        const props = this.props;
        props.form.setAllFormValue({ [config.headcode]: data.head[config.headcode] });
        if (data.body && data.body[config.bodycode]) {
            props.cardTable.setTableData(config.bodycode, data.body[config.bodycode]);
        } else {
            props.cardTable.setTableData(config.bodycode, { rows: [] });
        }
        if (!props.getUrlParam('id')) {
            props.setUrlParam({
                id: _.get(data, `head.${config.headcode}.rows[0].values.pk_costshare.value`, '')
            });
        }
        this.setBillStatus();
    }

    // 审核状态
    // public static final int DJZT_TempSaved = 0;  //单据状态——暂存
    // public static final int DJZT_Saved = 1; //单据状态——保存
    // public static final int DJZT_Verified = 2;//单据状态——审核
    // public static final int DJZT_Sign = 3; //单据状态——签字
    // public static final int DJZT_Invalid = -1; //单据状态——作废
    setBillStatus() {
        const props = this.props;
        const billstatus = props.form.getFormItemsValue(config.headcode, 'billstatus');
        const srcType = props.form.getFormItemsValue(config.headcode, 'src_type');
        if (srcType.value === '0') {
            if (billstatus.value === '0') {
                props.button.setButtonDisabled(['approve_group'], true);
            } else if (billstatus.value === '1') {
                props.button.setButtonDisabled(['unapprove'], true);
                props.button.setButtonDisabled(['approve_group', 'approve'], false);
            } else if (billstatus.value === '3') {
                props.button.setButtonDisabled(['edit', 'delete', 'approve'], true);
                props.button.setButtonDisabled(['approve_group', 'unapprove'], false);
            }
        } else {
            props.button.setButtonDisabled(['edit', 'delete', 'temp_save', 'save', 'cancel', 'approve_group'], true);
        }
    }

    checkValid() {
        const props = this.props;
        if (!props.form.isCheckNow(config.headcode)) {
            return;
        }
        if (!props.cardTable.checkTableRequired(config.bodycode)) {
            return;
        }
        const rows = props.cardTable.getVisibleRows(config.bodycode);
        const total = Number(props.form.getFormItemsValue(config.headcode, 'total').value);
        const input = rows.map(a => a.values.assume_amount.value).reduce((acc, cur) => Number(acc) + Number(cur), 0);
        if (total !== input) {
            toast({ color: 'warning', title: '报销金额不一致' }); /* 国际化处理： 请选择数据操作！*/
            return;
        }
        return true;
    }

    save() {
        const props = this.props;
        if (!this.checkValid()) return;

        const reqData = props.createMasterChildData(config.pagecode, config.headcode, config.bodycode);
        api.saveCostShare(reqData).then(data => {
            toast({
                color: 'success',
                content: '保存成功'
            }); /* 国际化处理： 查询成功，共,条*/
            this.setPageStatus('browse');
            this.setData(data);
        });
    }
    saveTemporarily() {
        const props = this.props;
        if (!this.checkValid()) return;

        const reqData = props.createMasterChildData(config.pagecode, config.headcode, config.bodycode);
        api.saveCostShareTemporarily(reqData).then(data => {
            toast({
                color: 'success',
                content: '保存成功'
            }); /* 国际化处理： 查询成功，共,条*/
            this.setPageStatus('browse');
            this.setData(data);
        });
    }

    delete(record) {
        const props = this.props;
        promptBox({
            color: 'warning',
            title: this.state.multilang['delete'] /* 国际化处理： 删除*/,
            content: this.state.multilang['confirm_delete_select'] /* 国际化处理： ​​确定要删除所选数据吗？*/,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: this.state.multilang['confirm'] /* 国际化处理： 确定*/,
            cancelBtnName: this.state.multilang['cancel'] /* 国际化处理： 取消*/,
            beSureBtnClick: () => {
                const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');
                api.deleteCostShare({ pks: pk.value || '' }).then(data => {
                    toast({
                        color: 'success',
                        content: this.state.multilang['operate_success']
                    });
                    props.pushTo('/', {
                        status: 'browse',
                        pagecode: config.pagecode
                    });
                });
            }
        });
    }

    approve(record) {
        const props = this.props;
        const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');

        api.approveCostShare({ pks: pk.value || '', pagecode: config.pagecode, from: 'card' }).then(data => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            this.setData(data);
        });
    }

    cancelApprove(record) {
        const props = this.props;
        const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');
        api.cancelApprovalCostShare({ pks: pk.value || '', pagecode: config.pagecode, from: 'card' }).then(data => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            this.setData(data);
        });
    }

    renderTableHead() {
        const props = this.props;
        const status = props.getUrlParam('status');
        if (status !== 'edit' && status !== 'add') {
            return null;
        }
        return (
            <div className="shoulder-definition-area">
                <div className="definition-icons">
                    {this.props.button.createButtonApp({
                        area: config.tableButtonArea, //按钮注册中的按钮区域
                        //buttonLimit: 5,
                        onButtonClick: onTableButtonClick.bind(this)
                    })}
                </div>
            </div>
        );
    }

    renderErrorCenterState() {
        const { props } = this;
        const { socket } = props;
        const status = props.form.getFormItemsValue(config.headcode, 'saga_status');
        if (!status || status.value !== '1') return null;

        this.props.button.toggleErrorStatus(config.pageButtonArea, {
            isError: true
        });

        const param = {
            headBtnAreaCode: config.pageButtonArea,
            formAreaCode: config.headcode,
            billtype: props.form.getFormItemsValue(config.headcode, 'saga_status').value,
            billpkname: config.billpkname,
            dataSource: config.datasource
        };
        return props.socket.connectMesg(param);
    }

    render() {
        const { cardTable, button, form, modal, BillHeadInfo } = this.props;
        // let { cardTable, form, button, modal, cardPagination, transferTable } = this.props;

        return (
            <div className="nc-bill-card">
                {this.renderErrorCenterState()}
                <div className="nc-bill-top-area">
                    <NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
                        <div className="header-title-search-area">
                            {BillHeadInfo.createBillHeadInfo({
                                title: this.state.multilang['card_page_title'],
                                backBtnClick: onBackButtonClick.bind(this)
                            })}
                        </div>
                        <div className="header-button-area">
                            {button.createErrorFlag({
                                headBtnAreaCode: config.pageButtonArea
                            })}
                            {button.createButtonApp({
                                area: config.pageButtonArea,
                                onButtonClick: onPageButtonClick.bind(this)
                            })}
                            {/* {createCardPagination({
                            handlePageInfoChange: this.pageInfoClick.bind(this),
                            dataSource: dataSource
                        })} */}
                        </div>
                    </NCDiv>
                    <div className="nc-bill-form-area">
                        {form.createForm(config.headcode, {
                            // onAfterEvent: afterEvent.bind(this),
                            // onBeforeEvent: formBeforeEvent.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-bill-bottom-area">
                    <div className="nc-bill-table-area">
                        {cardTable.createCardTable(config.bodycode, {
                            tableHead: this.renderTableHead.bind(this),
                            onAfterEvent: onTableAfterEvent.bind(this),
                            onBeforeEvent: onTableBeforeEvent.bind(this)
                        })}
                    </div>
                </div>

                {this.state.isInspectionShowed && (
                    <Inspection
                        show={this.state.isInspectionShowed}
                        sourceData={this.state.inspectionSourceData}
                        cancel={() => this.setState({ isInspectionShowed: false })}
                        affirm={() => this.setState({ isInspectionShowed: true })}
                    />
                )}
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
